package com.studypavilion.project;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private String led = "865197833/led";
    private String fan = "865197833/fan";
    private String buzzer = "865197833/buzzer";
    private String api_key = "5NotSJ4WF9HjTOL=aWnDMvzCv=Q=";

    private String temperature = "temperature";
    private String humidity = "humidity";
    private String illumination = "illumination";

    private static int ledState = 1, fanState = 1, buzState = 1, threadRun = 1, replyOk = 0, btn_smart_state = 0;

    private static final String TAG = "info";

    private TextView edtTemperature, edtHumidity, edtIllumination;

    private CheckBox btn_led, btn_fan, btn_buzzer;
    private Button btn_start, btn_smart;

    private ProgressBar progrBar_temp, progressBar_hum, progressBar_light;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_led = findViewById(R.id.btn_led);
        btn_fan = findViewById(R.id.btn_fan);
        btn_buzzer = findViewById(R.id.btn_buzzer);

        btn_start = findViewById(R.id.btn_start);
        btn_smart = findViewById(R.id.btn_smart);

        edtTemperature = findViewById(R.id.edtTemperature);
        edtHumidity = findViewById(R.id.edtHumidity);
        edtIllumination = findViewById(R.id.edtIllumination);

        progrBar_temp = findViewById(R.id.progrBar_temp);
        progressBar_hum = findViewById(R.id.progressBar_hum);
        progressBar_light = findViewById(R.id.progressBar_light);

        btn_led.setOnClickListener(MainActivity.this);
        btn_fan.setOnClickListener(MainActivity.this);
        btn_buzzer.setOnClickListener(MainActivity.this);
        btn_start.setOnClickListener(MainActivity.this);
        btn_smart.setOnClickListener(MainActivity.this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_led:
//                Toast.makeText(MainActivity.this,"灯", Toast.LENGTH_SHORT).show();
                if (ledState == 1){
                    releaseTopic(led, "1");
                    ledState = 0;
                    btn_led.setText("关灯");
                    if (btn_smart_state == 1){
                        btn_smart_state = 0;
                        btn_smart.setText("智能监测已关闭");
                        Toast.makeText(MainActivity.this, "智能监测已关闭", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    releaseTopic(led, "0");
                    ledState = 1;
                    btn_led.setText("开灯");
                    if (btn_smart_state == 1){
                        btn_smart_state = 0;
                        btn_smart.setText("智能监测已关闭");
                        Toast.makeText(MainActivity.this, "智能监测已关闭", Toast.LENGTH_SHORT).show();
                    }
                }

                break;
            case R.id.btn_fan:
//                Toast.makeText(MainActivity.this,"风扇", Toast.LENGTH_SHORT).show();
                if (fanState == 1){
                    releaseTopic(fan, "1");
                    fanState = 0;
                    btn_fan.setText("关风扇");
                    if (btn_smart_state == 1) {
                        btn_smart_state = 0;
                        btn_smart.setText("智能监测已关闭");
                        Toast.makeText(MainActivity.this, "智能监测已关闭", Toast.LENGTH_SHORT).show();
                    }

                } else {
                    releaseTopic(fan, "0");
                    fanState = 1;
                    btn_fan.setText("开风扇");
                    if (btn_smart_state == 1){
                        btn_smart_state = 0;
                        btn_smart.setText("智能监测已关闭");
                        Toast.makeText(MainActivity.this, "智能监测已关闭", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.btn_buzzer:
//                Toast.makeText(MainActivity.this,"蜂鸣器", Toast.LENGTH_SHORT).show();
                if (buzState == 1){
                    releaseTopic(buzzer, "1");
                    buzState = 0;
                    btn_buzzer.setText("关闭警报");
                    if (btn_smart_state == 1){
                        btn_smart_state = 0;
                        btn_smart.setText("智能监测已关闭");
                        Toast.makeText(MainActivity.this, "智能监测已关闭", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    releaseTopic(buzzer, "0");
                    buzState = 1;
                    btn_buzzer.setText("开启警报");
                    if (btn_smart_state == 1){
                        btn_smart_state = 0;
                        btn_smart.setText("智能监测已关闭");
                        Toast.makeText(MainActivity.this, "智能监测已关闭", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.btn_start:
                String btn_start_name = btn_start.getText().toString();
                if (btn_start_name.equals("开始")){
                    threadRun = 1;
                } else if (btn_start_name.equals("停止")){
                    threadRun = 0;
                }
                if (threadRun == 1){
                    threadRun();
                    btn_start.setText("停止");
                } else {
                    btn_start.setText("开始");
                    threadRun = 0;
                }
                break;
            case R.id.btn_smart:
                String btn_smart_name = btn_smart.getText().toString();
                if (btn_smart_name.equals("智能监测已关闭")){
                    btn_smart.setText("智能监测已开启");
                    btn_smart_state = 1;
                } else if (btn_smart_name.equals("智能监测已开启")){
                    btn_smart.setText("智能监测已关闭");
                    btn_smart_state = 0;

                }
                break;

        }

    }

    private void threadRun() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    if (threadRun == 0){
                        break;
                    }
                    subscribe(temperature);
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    if (threadRun == 0){
                        break;
                    }
                    subscribe(illumination);
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    if (threadRun == 0){
                        break;
                    }
                    subscribe(humidity);
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

            }
        }).start();

    }

    private void subscribe(String topic) {

        try {

            URL ur1 = new URL("http://api.heclouds.com/devices/865197833/datastreams/" + topic);
            HttpURLConnection urlConnection = (HttpURLConnection) ur1.openConnection() ;
            urlConnection.addRequestProperty("api-key", api_key);
            InputStream inputStream = urlConnection.getInputStream();
            InputStreamReader reader = new InputStreamReader(inputStream ,"UTF-8");
            BufferedReader bufferedReader = new BufferedReader(reader);
            StringBuffer buffer = new StringBuffer() ;
            String temp = null;
            while ((temp = bufferedReader.readLine()) != null){
                buffer.append(temp);
            }

            jsonOption(buffer);

            bufferedReader.close();
            reader.close();
            inputStream.close();
            Thread.sleep(1000);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    private void jsonOption(StringBuffer buf) {
        try {
            JSONObject obj = new JSONObject(String.valueOf(buf));
            JSONObject data = obj.getJSONObject("data");
            String id = data.getString("id");
            String current_value = data.getString("current_value");
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (id.equals("illumination")){
                        Log.i(TAG, "illumination: " + current_value);
                        edtIllumination.setText(current_value + "lx");
                        progressBar_light.setProgress(Integer.parseInt(current_value));
                        if (btn_smart_state == 1){
                            if (Integer.parseInt(current_value) >= 50){
                                releaseTopic(led, "0");

                                btn_led.setChecked(false);
                                ledState = 1;
                                btn_led.setText("开灯");


                            } else if (Integer.parseInt(current_value) < 50){
                                releaseTopic(led, "1");
                                ledState = 0;
                                btn_led.setChecked(true);
                                btn_led.setText("关灯");
                            }

                        }
                    }
                    if (id.equals("temperature")){
                        Log.i(TAG, "temperature: " + current_value);
                        edtTemperature.setText(current_value + "℃");
                        progrBar_temp.setProgress(Integer.parseInt(current_value));
                        if (btn_smart_state == 1){
                            if (Integer.parseInt(current_value) >= 30 && Integer.parseInt(current_value) <= 60){
                                if ( fanState == 1){
                                    releaseTopic(fan, "1");
                                    fanState = 0;
                                    btn_fan.setText("关风扇");
                                    btn_fan.setChecked(true);
                                }
                                if (buzState == 0){
                                    releaseTopic(buzzer, "0");
                                    buzState = 1;
                                    btn_buzzer.setText("开启警报");
                                    btn_buzzer.setChecked(false);
                                }

                            }
                            else if (Integer.parseInt(current_value) < 30){
                                if (fanState == 0){
                                    releaseTopic(fan, "0");
                                    fanState = 1;
                                    btn_fan.setText("开风扇");
                                    btn_fan.setChecked(false);
                                }
                                if (buzState == 0){
                                    releaseTopic(buzzer, "0");
                                    buzState = 1;
                                    btn_buzzer.setText("开启警报");
                                    btn_buzzer.setChecked(false);
                                }

                            } else if (Integer.parseInt(current_value) > 60){
                                if (buzState == 1){
                                    releaseTopic(buzzer, "1");
                                    buzState = 0;
                                    btn_buzzer.setText("关闭警报");
                                    btn_buzzer.setChecked(true);
                                }

                            }

                        }

                    }
                    if (id.equals(humidity)){
                        Log.i(TAG, "humidity: " + current_value);
                        edtHumidity.setText(current_value + "%rh");
                        progressBar_hum.setProgress(Integer.parseInt(current_value));
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void releaseTopic(String topic, String data) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("http://api.heclouds.com/mqtt?" + "topic=" + topic);
//            2、构建http请求对象 -->打开水闸
                    HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
//            3、设置请求方式
//            POST方法
                    urlConn.setRequestMethod("POST");
                    urlConn.setConnectTimeout(15000);
                    // 设置读取主机服务器返回数据超时时间：60000毫秒
                    urlConn.setReadTimeout(60000);
                    // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
                    urlConn.setDoOutput(true);
                    // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
                    urlConn.setDoInput(true);
                    urlConn.setRequestProperty("api-key", api_key);

                    urlConn.connect();

//          发送请求参数
                    OutputStream dos = urlConn.getOutputStream();

//            8、从输入流中，将数据按照 "UTF-8" 的编码格式保存到 InputStreamReader 流中
                    dos.write(data.getBytes(StandardCharsets.UTF_8));
                    dos.flush();
                    dos.close();
//                    判断请求是否成功
                    if (urlConn.getResponseCode() == 200){
//                        获取返回的数据
                        String result = urlConn.getInputStream().toString();
                        replyOk = 1;
                    }else {
                        replyOk = 0;
                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

